import { useContext } from "react";
import { LowCodeDesignerContext } from "./Provider";
import { cloneDeep, findItemById } from "../shared";
import { produce } from "immer";
import { LowCodeContext } from "../core/Provider";

const useDesignerActions = () => {
  const { currentDesigner } = useContext(LowCodeDesignerContext);
  const { setItems, items } = useContext(LowCodeContext);

  const updateDesigner = (items) => {
    // // @ts-ignore
    // window.items = items;
    setItems({ ...items });
  };

  const addMaterialToDesigner = (item) => {
    const id = currentDesigner._id;
    // items.childen.push(schema)
    // setItems({...items})
    const nextState = produce(items, (draft) => {
      const findItem = findItemById([draft], id);
      if (findItem) {
        if (!findItem.children) {
          findItem.children = [];
          console.log("为空");
        } else if (!Array.isArray(findItem.children)) {
          findItem.children = [findItem.children];
          console.log("不是数组");
        } else {
          console.log("为else空");
        }
        console.log("findItemfindItem", findItem);
        findItem.children.push(item);
      } else {
        console.log("没找到啊");
      }
      //   item.props = {
      //     ...props,
      //     ...values,
      //   }
      //   if (children) {
      //     item.children = children
      //   }
    });

    updateDesigner(nextState);
  };
  // const moveMaterial = (sourceKey:string,targetKey:)=>{

  // }
  const copyMaterialToDesigner = () => {
    const item = cloneDeep(currentDesigner);

    items.push(item);
    setItems({ ...items });
  };
  return {
    updateDesigner,
    addMaterialToDesigner,
    copyMaterialToDesigner,
  };
};
export default useDesignerActions;
